import { defineComponent, onMounted, ref, watch } from "vue";
import { childrenByCode } from "@/api/dict";

export default defineComponent({
  name: "DictSelector",
  props: {
    modelValue: {
      type: Object,
    },
    code: {
      type: String,
      required: true,
    },
    size: {
      default: "default",
      validator: (v: string) => ["default", "small", "large"].includes(v),
      string: ["default", "small", "large"],
    },
    type: {
      default: "",
      validator: (v: string) =>
        ["success", "warning", "info", "danger", ""].includes(v),
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const data = ref([]);
    const val = ref(props.modelValue);
    watch(val, newVal => emit("update:modelValue", newVal), {
      deep: true,
    });
    watch(
      () => props.modelValue,
      () => {
        val.value = props.modelValue;
      }
    );
    onMounted(() => {
      childrenByCode(props.code).then(res => {
        data.value = res;
      });
    });
    return () => (
      <>
        <el-select
          clearable
          v-model={val.value}
          placeholder={props.placeholder}
          size={props.size}
          multiple={props.multiple}
          collapse-tags={props.multiple}
          collapse-tags-tooltip={props.multiple}
        >
          {data.value.map(item => {
            return (
              <el-option key={item.code} label={item.label} value={item.code} />
            );
          })}
        </el-select>
      </>
    );
  },
});
